package com.android.fragmentdemo.util
import android.util.Log

class StepLoadCollectionUtil private constructor() {
    companion object {
        private const val TAG = "StepLoadCollectionUtil"
        private var step = 0
        private var initLoadCount = 0
        private var loadCountPerTime = 10
        private var loadFinished = false
        private lateinit var mDataSet: MutableList<String>
        private lateinit var mInitDataSet: MutableList<String>

        fun init(mDataSet: MutableList<String>, initLoadCount: Int) {
            this.mDataSet = mutableListOf()
            for (item in mDataSet) {
                this.mDataSet.add(item)
            }
            this.mInitDataSet = mDataSet.subList(0, initLoadCount.coerceAtMost(mDataSet.size))
            this.initLoadCount = initLoadCount
            loadFinished = initLoadCount >= mDataSet.size
        }

        fun updateLoadCountPerTime(loadCountPerTime: Int) {
            this.loadCountPerTime = loadCountPerTime
        }

        fun loadItem(): MutableList<String> {
            val startIndex = (step * loadCountPerTime + initLoadCount).coerceAtMost(mDataSet.size)
            val endIndex = (startIndex + loadCountPerTime).coerceAtMost(mDataSet.size)
            Log.d(TAG, "startIndex:${startIndex}---endIndex:${endIndex}")
            loadFinished = endIndex >= mDataSet.size
            step++
            return mDataSet.subList(startIndex, endIndex)
        }

        fun getInitDataSet() = mInitDataSet

        fun hadLoadFinished() = loadFinished

        fun reset() {
            loadFinished = false
            step = 0
        }
    }
}